﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraSplashScreen;

namespace PRO_DOCS.DocumentManagementSystem.ADMIN.WIN.Configurations.Departments
{
    public partial class SynchroniseFolders : BLL.WIN.Templates.DevxConfigurationTemplate
    {
        public FoldersSynchronisingOptions SELECTED_FOLDER_SYNCHRONISE_OPTION
        { get; set; }
        public enum FoldersSynchronisingOptions
        {
            N_A = 0,
            IMPORT,
            EXPORT
        }

        bool _cONTINUE_UPLOADING;
        bool CONTINUE_UPLOADING
        {
            get { return _cONTINUE_UPLOADING; }
            set
            {
                _cONTINUE_UPLOADING = value;
                btnSaveUpdate.Enabled = value;
            }
        }

        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT _cURRENT_SELECTED_ARCHIVE_DEPARTMENT;
        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT CURRENT_SELECTED_ARCHIVE_DEPARTMENT
        {
            get { return _cURRENT_SELECTED_ARCHIVE_DEPARTMENT; }
            set
            {
                _cURRENT_SELECTED_ARCHIVE_DEPARTMENT = value;
                CURRENT_ARCHIVES_COPYING_FOLDERS = new List<string>();
                CONTINUE_UPLOADING = false;

                if (_cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID != 0)
                {
                    List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHE> aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES = _cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs.ToList();

                    for (int i = 0; i < aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES.Count; i++)
                    {
                        if (new DirectoryInfo(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).Exists)
                        {
                            CONTINUE_UPLOADING = true;
                            CURRENT_ARCHIVES_COPYING_FOLDERS.Add(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH);
                        }
                    }

                    if (!CONTINUE_UPLOADING)
                    {
                        MessageBox.Show
                            (
                                string.Format("The storage media for the \"{0}\" department was not found.{1}Please make sure that you are connected to the network or contact your network administrator", _cURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME, Environment.NewLine),
                                "Storage Media was not found",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning
                            );
                    }


                }
            }
        }
        List<string> CURRENT_ARCHIVES_COPYING_FOLDERS
        {
            get;
            set;
        }
        Dictionary<int, DAL.Database.ARCHIVE_DEPARTMENT> ArchiveDepartmentsList
        { get; set; }

        public SynchroniseFolders(FoldersSynchronisingOptions sELECTED_FOLDER_SYNCHRONISE_OPTION)
        {
            InitializeComponent();

            SELECTED_FOLDER_SYNCHRONISE_OPTION = sELECTED_FOLDER_SYNCHRONISE_OPTION;

            ArchiveDepartmentsList = new Dictionary<int, DAL.Database.ARCHIVE_DEPARTMENT>();
            btnSaveUpdate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(btnSaveUpdate_ItemClick);

            List<DAL.Database.ARCHIVE_DEPARTMENT> archiveDepartmentsList = PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTs.ToList();

            comboDepartments.Properties.Items.BeginUpdate();
            comboDepartments.Properties.Items.Clear();
            for (int i = 0; i < archiveDepartmentsList.Count; i++)
            {
                ArchiveDepartmentsList.Add(i, archiveDepartmentsList[i]);
                comboDepartments.Properties.Items.Add(archiveDepartmentsList[i].ARCHIVE_DEPARTMENT_NAME);
            }
            comboDepartments.Properties.Items.EndUpdate();
            comboDepartments.SelectedIndex = -1;
        }

        public void BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE()
        {
            try
            {
                trvDepartmentFolderStructure.Nodes.Clear();


                BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE(CURRENT_SELECTED_ARCHIVE_DEPARTMENT);

            }
            catch (Exception ex)
            {
                string abc = ex.Message;
            }

        }

        public void EXPORT_ARCHIVE_DEPARTMENT_FILES(Guid aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID, string cURRENT_EXPORTING_FOLDER)
        {
            List<DAL.Database.ARCHIVE_DEPARTMENT_FILE> aRCHIVE_DEPARTMENT_FILES = (from files in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILEs
                                                                                   where files.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value.Equals(aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID)
                                                                                   select files).ToList();

            for (int i = 0; i < aRCHIVE_DEPARTMENT_FILES.Count; i++)
            {
                //get the latest file history
                DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY file_histories = (
                                                                                        from histories in PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENT_FILE_HISTORies
                                                                                        where histories.ARCHIVE_DEPARTMENT_FILE_ID.Value.Equals(aRCHIVE_DEPARTMENT_FILES[i].ARCHIVE_DEPARTMENT_FILE_ID)
                                                                                        orderby histories.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value descending
                                                                                        select histories
                                                                                    ).FirstOrDefault();


                string originalFileName = file_histories.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID.ToString();
                string destinationFileName = file_histories.ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME + file_histories.ARCHIVE_DEPARTMENT_FILE_EXTENSION;

                FileInfo copyingFileInfo = null;

                for (int fls = 0; fls < CURRENT_ARCHIVES_COPYING_FOLDERS.Count; fls++)
                {
                    string filePath = Path.Combine(CURRENT_ARCHIVES_COPYING_FOLDERS[fls], originalFileName);

                    copyingFileInfo = new FileInfo(filePath);

                    if (copyingFileInfo.Exists)
                    {
                        break;
                    }
                    else
                    {
                        copyingFileInfo = null;
                    }
                }
                if (copyingFileInfo != null)
                {
                    string destinationFullPath = Path.Combine(cURRENT_EXPORTING_FOLDER, destinationFileName);
                    copyingFileInfo.CopyTo(destinationFullPath, true);

                    destinationFullPath = destinationFullPath.Replace(txtParentFolder.Text + "\\", string.Empty);
                    new ExportingXMLFiles().CREATE_DOCUMENT_XML_FILE
                        (
                            aRCHIVE_DEPARTMENT_FILES[i],
                            file_histories,
                            destinationFullPath,
                            txtParentFolder.Text,
                            PRO_DOCSDatabaseDataContext
                        );
                }
            }
        }

        private void EXPORT_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, string strParentFolder)
        {

            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREs.ToList();

            for (int i = 0; i < aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Count; i++)
            {
                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES[i];

                string subArciveFolder = Path.Combine(strParentFolder, _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME);

                new DirectoryInfo(subArciveFolder).Create();

                if (chkSaveIncludingFiles.Checked)
                {
                    EXPORT_ARCHIVE_DEPARTMENT_FILES(_aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID, subArciveFolder);
                }

                EXPORT_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(_aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, subArciveFolder);

            }
        }

        private void BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, TreeListNode trParentNode)
        {

            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREs.ToList();

            for (int i = 0; i < aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Count; i++)
            {
                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES[i];
                TreeListNode tlFolderNode = trvDepartmentFolderStructure.AppendNode(new object[] { _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME, ApplicationStructureTypes.Folder, FolderTypes.Folder, 10, _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID }, trParentNode, _aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);

                BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(_aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, tlFolderNode);

            }
        }

        bool IS_FIRST_LOAD;

        public void BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE(PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT aRCHIVE_DEPARTMENT)
        {
            IS_FIRST_LOAD = true;
            CURRENT_SELECTED_ARCHIVE_DEPARTMENT = aRCHIVE_DEPARTMENT;

            trvDepartmentFolderStructure.Nodes.Clear();

            TreeListNode tlnDepartmentNode = trvDepartmentFolderStructure.AppendNode(new object[] { CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME, ApplicationStructureTypes.Department, FolderTypes.Folder, 12, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID }, null, CURRENT_SELECTED_ARCHIVE_DEPARTMENT);

            {
                //Gets the 1st Level
                List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREs.ToList();


                for (int i = 0; i < aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Count; i++)
                {
                    PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES[i];

                    if (aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.PARENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value.Equals(Guid.Empty))
                    {
                        TreeListNode tlFolderNode = trvDepartmentFolderStructure.AppendNode(new object[] { aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME, ApplicationStructureTypes.Folder, FolderTypes.Folder, 10, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID }, tlnDepartmentNode, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);


                        BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, tlFolderNode);

                    }
                }

            }

            trvDepartmentFolderStructure.ExpandAll();
            IS_FIRST_LOAD = false;
        }


        void btnSaveUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (comboDepartments.SelectedIndex > -1)
            {
                SplashScreenManager.ShowForm(typeof(WaitForm1), true, true);

                switch (SELECTED_FOLDER_SYNCHRONISE_OPTION)
                {
                    case FoldersSynchronisingOptions.IMPORT:
                        #region IMPORT FILES AND FOLDERS
                        {
                            // Add the directories and files
                            foreach (KeyValuePair<Guid, DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> sINGLE_FOLDER in ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES)
                            {
                                //1. Add the directories
                                sINGLE_FOLDER.Value.ARCHIVE_DEPARTMENT_ID = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID;
                                //PRO_DOCSDatabaseDataContext.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREs.InsertOnSubmit(sINGLE_FOLDER.Value);
                                //PRO_DOCSDatabaseDataContext.SubmitChanges();
                                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREInsert
                                    (
                                        sINGLE_FOLDER.Value.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID,
                                        sINGLE_FOLDER.Value.ARCHIVE_DEPARTMENT_ID,
                                        sINGLE_FOLDER.Value.PARENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value,
                                        sINGLE_FOLDER.Value.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME,
                                        false);
                                //2. Add the files
                                if (chkSaveIncludingFiles.Checked)
                                {
                                    if (ARCHIVE_DEPARTMENT_FILES.ContainsKey(sINGLE_FOLDER.Key))
                                    {
                                        List<FileInfo> folder_files = ARCHIVE_DEPARTMENT_FILES[sINGLE_FOLDER.Key];
                                        for (int i = 0; i < folder_files.Count; i++)
                                        {
                                            bool fileUploaded = false;

                                            //the new fileId to be named with
                                            string newCreatedPhysicalFileName = Guid.NewGuid().ToString(); //uploadedPhysicalFiles.FileId.ToString();
                                            //the original file path
                                            FileInfo currentConsumedFile = folder_files[i];
                                            //a. copy the file

                                            for (int fc = 0; fc < CURRENT_ARCHIVES_COPYING_FOLDERS.Count; fc++)
                                            {
                                                try
                                                {
                                                    currentConsumedFile.CopyTo(Path.Combine(CURRENT_ARCHIVES_COPYING_FOLDERS[fc], newCreatedPhysicalFileName));
                                                    fileUploaded = true;
                                                    break;
                                                }
                                                catch (Exception ex)
                                                {
                                                    MessageBox.Show(ex.Message);
                                                }
                                            }

                                            if (fileUploaded)
                                            {
                                                //2. ADD the file table
                                                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE aRCHIVE_DEPARTMENT_FILE = new DAL.Database.ARCHIVE_DEPARTMENT_FILE();
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID = Guid.NewGuid();
                                                //--------->aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID;
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = sINGLE_FOLDER.Key; //CURRENT_SELECTED_DESTINATION_ARCHIVE_DEPARTMENTS_FOLDER.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID;
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME = currentConsumedFile.Name.Replace(currentConsumedFile.Extension, string.Empty);
                                                //---------->get the document type
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DOCUMENT_TYPE_ID = null;// ARCHIVE_DEPARTMENT_DOCUMENT_TYPES[comboDocumentTypes.SelectedIndex].ARCHIVE_DOCUMENT_TYPE_ID;
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE = BLL.WIN.Utilities.FileType.GenerateRandomBarcode();
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE = DateTime.Now;
                                                aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED = false;
                                                aRCHIVE_DEPARTMENT_FILE.IS_DELETED = false;

                                                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILESInsert
                                                    (
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE.Value,
                                                    BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME,
                                                    null,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NOTES,
                                                    aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED.Value,
                                                    aRCHIVE_DEPARTMENT_FILE.IS_DELETED.Value
                                                    );

                                                //1. ADD The file history
                                                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY aRCHIVE_DEPARTMENT_FILE_HISTORY = new DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY();
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = Guid.Parse(newCreatedPhysicalFileName);// uploadedPhysicalFiles.FileId;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID = aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID;
                                                //aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = Guid.NewGuid();
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID = 1;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME = currentConsumedFile.Name;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION = currentConsumedFile.Extension;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID = PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE = currentConsumedFile.Length;
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE = DateTime.Now;

                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED = false;


                                                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_HISTORYInsert
                                                (
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID.Value,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID.Value,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID.Value,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.Value,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_NOTES,
                                                aRCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED.Value);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                        break;
                    case FoldersSynchronisingOptions.EXPORT:
                        #region EXPORT FILES AND FODLERS
                        {
                            EXPORT_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE();
                        }
                        #endregion
                        break;
                }
                SplashScreenManager.CloseForm();

                XtraMessageBox.Show("Synchronisation Finished Successfully", "Synchronisation Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                dxErrorProvider1.SetError(comboDepartments, BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Department"));
            }
        }

        public void GET_FOLDER_STRUCTURE(string parentFolder)
        {

            ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES = new Dictionary<Guid, DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE>();
            ARCHIVE_DEPARTMENT_FILES = new Dictionary<Guid, List<FileInfo>>();

            if (Directory.Exists(parentFolder))
            {
                DirectoryInfo direParent = new DirectoryInfo(parentFolder);
                Guid current_folder_id = Guid.NewGuid();
                DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = new DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE();
                aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = current_folder_id;
                aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME = direParent.Name;
                aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.PARENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = Guid.Empty;
                aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.IS_DELETED = false;
                ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Add(current_folder_id, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);
                // This path is a directory
                TreeListNode tlFolderNode = trvDepartmentFolderStructure.AppendNode(new object[] { aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME, ApplicationStructureTypes.Folder, FolderTypes.Folder, 10, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID }, null, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);
                ProcessDirectory(parentFolder, current_folder_id, tlFolderNode);

                // get the files
                string[] fileEntries = Directory.GetFiles(parentFolder);
                foreach (string fileName in fileEntries)
                    ProcessFile(fileName, current_folder_id);


                tlFolderNode.ExpandAll();
            }


        }

        Dictionary<Guid, DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES
        { get; set; }

        // Insert logic for processing found files here. 
        public void ProcessFile(string path, Guid current_folder_id)
        {
            FileInfo fiProcessedFile = new FileInfo(path);

            List<FileInfo> folderFiles = new List<FileInfo>();

            if (!ARCHIVE_DEPARTMENT_FILES.ContainsKey(current_folder_id))
            {
                ARCHIVE_DEPARTMENT_FILES.Add(current_folder_id, folderFiles);
            }
            else
            {
                folderFiles = ARCHIVE_DEPARTMENT_FILES[current_folder_id];
            }
            folderFiles.Add(fiProcessedFile);
            ARCHIVE_DEPARTMENT_FILES[current_folder_id] = folderFiles;
        }

        // Process all files in the directory passed in, recurse on any directories  
        // that are found, and process the files they contain. 
        public void ProcessDirectory(string targetDirectory, Guid current_folder_id, TreeListNode parentNode)
        {
            // Recurse into subdirectories of this directory. 
            List<string> subdirectoryEntries = Directory.GetDirectories(targetDirectory).ToList();
            foreach (string subdirectory in subdirectoryEntries)
            {
                //Gets the 1st Level
                {
                    DirectoryInfo direParent = new DirectoryInfo(subdirectory);
                    Guid current_new_folder_id = Guid.NewGuid();
                    DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = new DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE();
                    aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = current_new_folder_id;
                    aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME = direParent.Name;
                    aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.PARENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = current_folder_id;
                    aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.IS_DELETED = false;
                    ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Add(current_new_folder_id, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);
                    // This path is a directory
                    {
                        TreeListNode tlFolderNode = trvDepartmentFolderStructure.AppendNode(new object[] { aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME, ApplicationStructureTypes.Folder, FolderTypes.Folder, 10, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID }, parentNode, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE);


                        ProcessDirectory(subdirectory, current_new_folder_id, tlFolderNode);

                    }
                }

            }

            //// Process the list of files found in the directory. 
            string[] fileEntries = Directory.GetFiles(targetDirectory);
            foreach (string fileName in fileEntries)
                ProcessFile(fileName, current_folder_id);

        }

        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "Select the parent folder where you want to synchrinise";
            if (fbd.ShowDialog().Equals(DialogResult.OK))
            {
                //trvDepartmentFolderStructure.Nodes.Clear();
                txtParentFolder.Text = fbd.SelectedPath;
                switch (SELECTED_FOLDER_SYNCHRONISE_OPTION)
                {
                    case FoldersSynchronisingOptions.IMPORT:
                        {
                            GET_FOLDER_STRUCTURE(fbd.SelectedPath);
                        }
                        break;
                    case FoldersSynchronisingOptions.EXPORT:
                        break;
                }
            }
        }

        public Dictionary<Guid, List<FileInfo>> ARCHIVE_DEPARTMENT_FILES { get; set; }

        private void comboDepartments_SelectedIndexChanged(object sender, EventArgs e)
        {
            IS_FIRST_LOAD = false;
            if (comboDepartments.SelectedIndex > -1)
            {

                CURRENT_SELECTED_ARCHIVE_DEPARTMENT = ArchiveDepartmentsList[comboDepartments.SelectedIndex];

                BUILD_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE();
            }
        }



        private void EXPORT_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE()
        {
            IS_FIRST_LOAD = true;

            //1. Create the department directory
            string departmentFullDirectory = Path.Combine(txtParentFolder.Text, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME);

            new DirectoryInfo(departmentFullDirectory).Create();


            //TreeListNode tlnDepartmentNode = trvDepartmentFolderStructure.AppendNode(new object[] { CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME, ApplicationStructureTypes.Department, FolderTypes.Folder, 12, CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_ID }, null, CURRENT_SELECTED_ARCHIVE_DEPARTMENT);

            {
                //Gets the 1st Level
                List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE> aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES = CURRENT_SELECTED_ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTUREs.ToList();


                for (int i = 0; i < aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES.Count; i++)
                {
                    PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURES[i];

                    if (aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.PARENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value.Equals(Guid.Empty))
                    {
                        string frstFolderFullPath = Path.Combine(departmentFullDirectory, aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME);

                        new DirectoryInfo(frstFolderFullPath).Create();

                        if (chkSaveIncludingFiles.Checked)
                        {
                            EXPORT_ARCHIVE_DEPARTMENT_FILES(aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID, frstFolderFullPath);
                        }
                        EXPORT_ARCHIVE_DEPARTMENT_FOLDER_STRUCTURE_FOLDERS_SUBFOLDERS(aRCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE, frstFolderFullPath);

                    }
                }

            }


            IS_FIRST_LOAD = false;
        }


        private void SynchroniseFolders_Load(object sender, EventArgs e)
        {

        }

        private void trvDepartmentFolderStructure_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {

        }

    }
}